import request from '@/utils/request'
import { onMounted, ref } from 'vue'

export type FetchOptions = {
  method?: 'POST' | 'GET'

  manual?: boolean
  defaultParams?: Record<string, any>
  headers?: Record<string, any>
  otherOptions?: Record<string, any>


  onAfter?: (res: any) => any
  onSuccess?: (res: any, params: any) => any
}

export default <TData>(
  url: string,
  {
    defaultParams,
    manual,
    method = 'GET',
    headers,
    otherOptions,
    onAfter,
    onSuccess,
  }: FetchOptions = {},
) => {
  const loading = ref(false)
  const data = ref<TData>()
  const error = ref()
  const lastParams = ref()

  const execute = async (params: any) => {
    lastParams.value = params
    try {
      loading.value = true
      let res = await request(url, method, { data: params, headers, ...otherOptions })
      res = onAfter ? onAfter(res) : res
      data.value = res
      onSuccess?.(res, params)
    } catch (err) {
      error.value = err
      console.error(err)
    } finally {
      loading.value = false
    }
  }

  const run = (params?: any) => execute(params)

  const refresh = () => execute(lastParams.value)

  onMounted(() => {
    if (!manual) {
      execute(defaultParams)
    }
  })

  return {
    data,
    error,
    loading,
    run,
    refresh,
  }
}
